package com.yixia.framework.security;

import com.yixia.common.core.domain.entity.SysUser;
import com.yixia.common.enums.UserStatus;
import com.yixia.common.exception.user.UserCountLockException;
import com.yixia.common.core.domain.model.LoginUser;

import com.yixia.common.utils.StringUtils;
import com.yixia.framework.web.service.SysPasswordService;
import com.yixia.framework.web.service.SysPermissionService;
import com.yixia.system.service.system.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * 自定义UserDetails
 */
@Service
@Slf4j
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysPasswordService passwordService;

    /**/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        /*根据username查询出用户*/
        SysUser sysUser = userService.getByUsername(username);
        if(StringUtils.isNull(sysUser)){
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("用户名不存在！");
        }
        else if("1".equals(sysUser.getStatus())){
            /*该用户被禁用了*/
            throw new UserCountLockException("此用户被禁用了，请联系管理员");
        }else if(UserStatus.DELETED.getCode().equals(sysUser.getStatus())){
            /*该用户被删除了*/
            log.info("该用户被删除了，{}，这种情况其实不会发生！！！", username);
            throw new UserCountLockException("此用户被删除了，请联系管理员");
        }

        /*用户情况---用户被删除后是查找不到的*/
        /*1. 用户不存在*/
        /*2. 用户被禁用*/
        /*3. 用被停用---由于查找时不查找del_fag这个字段，不会出现这种情况*/
        passwordService.validate(sysUser);/*密码错误次数拦截*/

        UserDetails loginUser = createLoginUser(sysUser);
        return loginUser;
    }

    public UserDetails createLoginUser(SysUser user)
    {
        /*将SysUser封装成登录LoginUser*/
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }
}
